const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
const https = require("https");
const cheerio = require("cheerio");

var reqUrl = "https://maoyan.com/films";
var arr = [];

http.createServer((req, res) => {
    var urlObj = url.parse(req.url);
    var pathname = urlObj.pathname;
    if (pathname == "/") {
        var filePath = path.join(__dirname, "/index.html");
        fs.readFile(filePath, (err, data) => {
            if (err) {
                console.log(err);
            } else {
                res.writeHead(200, { "Content-Type": "text/html;charset=utf-8;" });
                res.write(data);
                res.end();
            }
        });
    } else if (pathname == "/getlist") {
        https.get(reqUrl, (r) => {
            var str = "";
            r.on("data", (chunk) => {
                str += chunk;
            });
            r.on("end", () => {
                console.log(str);
                var $ = cheerio.load(str);
                $(".movie-item-title a").each((i, el) => {
                    var obj = {};
                    obj.movieId = $(el).attr("data-val").split(":")[1].slice(0, -1);
                    obj.movieName = $(el).text();
                    var num1 = $(el).parent().next().text();
                    // var num1 = $(el).parent().next().children(".integer").text();
                    // var num2 = $(el).parent().next().children(".fraction").text();
                    obj.movieOrange = num1;
                    arr.push(obj);
                });
                res.writeHead(200, { "Content-Type": "text/plain" });
                res.write(JSON.stringify(arr));
                res.end();
            });
        });
    }
}).listen(8082);

console.log("server is listening 8082");
